<template>
  <div>
    <el-dialog
      :title="showInfoTitle"
      :visible.sync="show"
      width="40rem"
      :before-close="closeDialog"
    >
      <div class="from-infomations">
        <el-form
          ref="form"
          label-position="left"
          label-width="5rem"
        >
          <el-form-item label="考勤名称" required>
            <el-input
              v-model="attendanceInfo.checkName"
              clearable
              maxlength="10"
              show-word-limit
              style="width:25rem"
            />
          </el-form-item>
          <el-form-item label="考勤位置" required>
            <span style="margin-right:1rem">{{ attendanceInfo.checkPosition }}</span>
            <el-button type="primary" @click="showSelectLocation()">选择位置</el-button>
          </el-form-item>
          <el-form-item label="签到时间" label-width="5rem" required>
            <el-date-picker
              v-model="attSendTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item label="位置距离" required>
            <el-input
              v-model="attendanceInfo.checkQrcode"
              style="width:25rem"
              placeholder="请输入位置距离"
              clearable
              oninput="value=value.replace(/^\.+|[^\d.-]/g,'')"
              maxlength="5"
              show-word-limit
            />千米
          </el-form-item>
          <el-form-item label="考勤状态" required>
            <el-radio-group v-model="attendanceInfo.checkStatus">
              <el-radio :label="1">发布</el-radio>
              <el-radio :label="2">不发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="分数设置" required>
            <el-radio-group v-model="setScore">
              <el-radio label="1">设置分数</el-radio>
              <el-radio label="2">不设置分数</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="setScore === '1'" label="考核分数" required>
            <el-input
              v-model="attendanceInfo.checkScore"
              style="width:25rem"
              placeholder="请输入分数"
              clearable
              oninput="value=value.replace(/^\.+|[^\d.-]/g,'')"
              maxlength="5"
              show-word-limit
              @input="changeSendScore"
            />
          </el-form-item>
          <el-form-item label="评分类型" required>
            <div v-for="item in attendanceTypeInfo" :key="item.checkId" style="display:flex;margin-bottom:1rem">
              <el-checkbox v-model="item.typeStatus" :disabled="item.checkName==='正常'?true:false" style="margin-right:2rem">{{ item.checkName }}</el-checkbox>
              <span v-if="item.checkName==='正常'">和正常分数一致</span>
              <el-input
                v-else-if="item.checkName!=='正常'"
                v-model="item.checkTypeScore"
                style="width:8rem"
                :placeholder="item.checkName==='未到'?0:item.checkName==='迟到'?Math.round(attendanceInfo.checkScore*0.8*10)/10:item.checkName==='早退'?Math.round(attendanceInfo.checkScore*0.8*10)/10:0"
                oninput="value=value.replace(/^\.+|[^\d.-]/g,'')"
                maxlength="4"
                show-word-limit
                clearable
              />
              <span v-if="item.checkName!=='正常'" style="margin-left:1rem">分</span>
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="attendanceInfo.checkRemark"
              type="textarea"
              style="width:25rem"
              autosize
              placeholder="请输入备注"
            />
          </el-form-item>
          <el-form-item v-if="sendStatus===1" label="管理员姓名" label-width="6rem">
            {{ attendanceInfo.checkAdminUserName }}
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="sendDialog()">确 定</el-button>
      </span>
    </el-dialog>
    <select-location ref="selectLocation" @setLocation="setLocation" />
  </div>
</template>
<script>
import { getAllInfo } from '../../api/user.js'
import { deepClone } from '../../utils/deepClone.js'
import { isOpenSendTime } from '../../utils/isOpenSendTime.js'
import { addessay, updateattendance } from '../../api/checkAttendance.js'
import { getCheckTypeByCheckId, updatecheckType, deletecheckType, addAttendance } from '../../api/checkType.js'
import selectLocation from '../selectLocation/selectLocation.vue'
export default {
  components: {
    'select-location': selectLocation
  },
  data() {
    return {
      // 动态数据存储位置
      sendStatus: '', // 提交状态 0新增 1修改
      attendanceInfo: {}, // 考勤详细信息
      attendanceTypeInfo: [], // 考勤类型详细信息
      attendanceTypeOldInfo: [], // 考勤类型信息缓存
      attSendTime: [], // 考勤开始结束时间
      setScore: '',
      checkAdminUserName: '',
      checkId: '',
      // 页面数据存储位置
      show: false, // dialog展示状态
      showInfoTitle: '', // 展示的标题信息
      input: ''
    }
  },
  created() {
    this.show = false
  },
  methods: {
    // 展示dialog弹出框
    showDialog(data, sendStatus) {
      this.show = true
      this.sendStatus = sendStatus
      var that = this
      if (sendStatus === 0) {
        // 新增
        that.attendanceInfo = {
          checkScore: 0
        }
        // 存储评分类型信息
        that.attendanceTypeInfo = [
          {
            checkName: '正常',
            checkScoreType: 1,
            checkTypeScore: null,
            typeStatus: true
          },
          {
            checkName: '未到',
            checkScoreType: 2,
            checkTypeScore: null,
            typeStatus: false
          },
          {
            checkName: '迟到',
            checkScoreType: 2,
            checkTypeScore: null,
            typeStatus: false
          },
          {
            checkName: '早退',
            checkScoreType: 2,
            checkTypeScore: null,
            typeStatus: false
          },
          {
            checkName: '病假',
            checkScoreType: 2,
            checkTypeScore: null,
            typeStatus: false
          },
          {
            checkName: '事假',
            checkScoreType: 2,
            checkTypeScore: null,
            typeStatus: false
          }
        ]
        that.showInfoTitle = '新增考勤信息'
        that.attSendTime = []
      } else {
        // 更新
        that.attendanceInfo = deepClone(data)
        // 保存原始数据
        // 根据考勤编号获取考勤信息
        getCheckTypeByCheckId(data.checkId).then((res) => {
          // 存储考勤信息
          const attendanceTypeInfo = [
            {
              checkName: '正常',
              checkScoreType: 1,
              checkTypeScore: data.checkScore,
              typeStatus: true
            },
            {
              checkName: '未到',
              checkScoreType: 2,
              checkTypeScore: null,
              typeStatus: false
            },
            {
              checkName: '迟到',
              checkScoreType: 2,
              checkTypeScore: null,
              typeStatus: false
            },
            {
              checkName: '早退',
              checkScoreType: 2,
              checkTypeScore: null,
              typeStatus: false
            },
            {
              checkName: '病假',
              checkScoreType: 2,
              checkTypeScore: null,
              typeStatus: false
            },
            {
              checkName: '事假',
              checkScoreType: 2,
              checkTypeScore: null,
              typeStatus: false
            }
          ]
          for (const j in attendanceTypeInfo) {
            attendanceTypeInfo[j].checkAttendanceId = data.checkId
            for (const i in res.obj) {
              if (res.obj[i].checkName === attendanceTypeInfo[j].checkName) {
                res.obj[i].typeStatus = true
                attendanceTypeInfo[j] = res.obj[i]
                break
              }
            }
          }
          that.attendanceTypeInfo = attendanceTypeInfo
          that.attendanceTypeOldInfo = attendanceTypeInfo
        })
        that.showInfoTitle = '考勤信息详情'
        if (that.attSendTime !== []) {
          that.attSendTime = []
        }
        if (that.attendanceInfo.checkScore === null || that.attendanceInfo.checkScore === 0) {
          that.setScore = '2'
        } else {
          that.setScore = '1'
        }

        that.attSendTime[0] = data.checkStartTime
        that.attSendTime[1] = data.checkStopTime
      }

      // 获取当前人员姓名
      getAllInfo(sessionStorage.getItem('userId')).then(function(res) { that.checkAdminUserName = res.obj.userinfo.userName })
    },
    // 关闭dialog
    closeDialog() {
      this.$confirm('是否确定关闭', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.show = false
        this.attendanceInfo = {}
        this.attendanceTypeInfo = []
        this.attSendTime = []
        this.setScore = ''
      }).catch(() => {})
    },
    // 提交dialog
    sendDialog() {
      var that = this
      const sendStatus = that.sendStatus
      isOpenSendTime().then((res) => {
        that.timeType = res
        if (that.timeType === 1) {
          var attendanceInfo = that.attendanceInfo
          var attSendTime = that.attSendTime
          if (that.setScore === '2') {
            that.attendanceTypeInfo[0].checkTypeScore = 0
          }
          if (attendanceInfo.checkName === '' || attendanceInfo.checkName === undefined) {
            that.$message({
              message: '请填写考勤名称',
              type: 'warning'
            })
          } else if (attendanceInfo.checkPosition === '' || attendanceInfo.checkPosition === undefined) {
            that.$message({
              message: '请填写考勤位置',
              type: 'warning'
            })
          } else if (attSendTime === null || attSendTime[0] === undefined || attSendTime[1] === undefined) {
            that.$message({
              type: 'warning',
              message: '请选择时间'
            })
          } else if (!attendanceInfo.checkStatus === '' || attendanceInfo.checkStatus === undefined) {
            that.$message({
              message: '请选择考勤状态',
              type: 'warning'
            })
          } else if (!attendanceInfo.checkQrcode) {
            that.$message({
              message: '请选择位置距离',
              type: 'warning'
            })
          } else if (that.setScore === '') {
            that.$message({
              message: '请选择分数设置',
              type: 'warning'
            })
          } else if ((that.setScore === '1' && attendanceInfo.checkScore === '') || (that.setScore === '1' && attendanceInfo.checkScore === undefined)) {
            that.$message({
              message: '请输入考核分数',
              type: 'warning'
            })
          } else {
            let sendTypeStatus = true
            for (const i in that.attendanceTypeInfo) {
              if (that.attendanceTypeInfo[i].typeStatus === true && that.attendanceTypeInfo[i].checkTypeScore === null || that.attendanceTypeInfo[i].checkTypeScore === '') {
                that.$message({
                  message: '请输入类型分数',
                  type: 'warning'
                })
                sendTypeStatus = false
                break
              }
            }
            if (sendTypeStatus === true) {
              that.$confirm('是否确定提交', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                that.$message('正在提交中')
                // 开始提交
                const attendance = {}
                attendance.checkName = attendanceInfo.checkName
                attendance.checkList = JSON.parse(sessionStorage.getItem('routerMessage')).routerLevel
                attendance.checkListId = JSON.parse(sessionStorage.getItem('routerMessage')).routerId
                attendance.checkStatus = attendanceInfo.checkStatus
                attendance.checkQrcode = attendanceInfo.checkQrcode
                attendance.checkSemId = sessionStorage.getItem('semId')
                attendance.checkPosition = attendanceInfo.checkPosition
                attendance.checkRemark = attendanceInfo.checkRemark
                attendance.checkStartTime = that.dateReSend(attSendTime[0])
                attendance.checkStopTime = that.dateReSend(attSendTime[1])
                attendance.checkAdminUserId = sessionStorage.getItem('userId')
                attendance.checkAdminUserName = that.checkAdminUserName
                attendance.checkLatitude = attendanceInfo.checkLatitude
                attendance.checkLongitude = attendanceInfo.checkLongitude
                if (that.setScore === '1') {
                  attendance.checkScore = attendanceInfo.checkScore
                } else {
                  attendance.checkScore = 0
                }
                // 判断提交状态
                if (sendStatus === 0) {
                  addessay(attendance).then((res) => {
                  // 更新考勤类型
                    that.checkId = res.obj
                    that.sendAttendanceTypeInfo(0)
                  })
                } else if (sendStatus === 1) {
                  attendance.checkId = attendanceInfo.checkId
                  attendance.checkQrcode = attendanceInfo.checkQrcode
                  updateattendance(attendance).then(() => {
                  // 更新考勤类型
                    that.checkId = attendance.checkId
                    that.sendAttendanceTypeInfo(1)
                  })
                }
              }).catch(() => {

              })
            }
          }
        } else if (that.timeType === 2) {
          that.$message({
            message: '未到开放时间',
            type: 'warning'
          })
        } else if (that.timeType === 3) {
          that.$message({
            message: '已过开放时间',
            type: 'warning'
          })
        } else {
          that.$message({
            message: '系统繁忙请联系管理员',
            type: 'warning'
          })
        }
      })
    },
    // 提交考勤类型信息
    sendAttendanceTypeInfo(type) {
      var that = this
      const attendanceTypeInfo = that.attendanceTypeInfo
      let updateStatus = false
      for (let i = 0; i < attendanceTypeInfo.length; i++) {
        if (attendanceTypeInfo[i].checkTypeId) {
          // 当前有数据，删除&更新
          if (attendanceTypeInfo[i].typeStatus === false) {
            // 删除
            deletecheckType(attendanceTypeInfo[i].checkTypeId).then(() => {
              if (i === attendanceTypeInfo.length - 1) {
                that._sendSuccess(type)
              }
            })
          } else {
            // 更新
            updatecheckType(attendanceTypeInfo[i]).then(() => {
              updateStatus = true
              if (i === attendanceTypeInfo.length - 1) {
                that.$confirm('更新成功，是否更新用户成绩，点击确定后更新', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  // 更新用户成绩
                  that.__updateUserScore(attendanceTypeInfo)
                }).catch(() => {
                  that._sendSuccess(type)
                  that.$message({
                    type: 'info',
                    message: '已取消更新'
                  })
                })
              }
            })
          }
        } else {
          // 新添数据
          if (attendanceTypeInfo[i].typeStatus === true) {
            // 判断是否为正常信息
            if (attendanceTypeInfo[i].checkName === '正常') {
              attendanceTypeInfo[i].checkTypeScore === that.attendanceInfo.checkScore
            }
            attendanceTypeInfo[i].checkAttendanceId = that.checkId
            addAttendance(attendanceTypeInfo[i]).then(() => {
              if (i === attendanceTypeInfo.length - 1) {
                that._sendSuccess(type)
              }
            })
          } else {
            if (i === attendanceTypeInfo.length - 1) {
              if (updateStatus === true) {
                that.$confirm('更新成功，是否更新用户成绩，点击确定后更新', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  // 更新用户成绩
                  that.__updateUserScore(attendanceTypeInfo)
                }).catch(() => {
                  that._sendSuccess(type)
                  that.$message({
                    type: 'info',
                    message: '已取消更新'
                  })
                })
              } else {
                that._sendSuccess(type)
              }
            }
          }
        }
      }
    },
    // 更新用户成功
    __updateUserScore(attendanceTypeInfo) {
      var that = this
      console.log(attendanceTypeInfo, that.attendanceTypeOldInfo)
    },
    // 关闭弹出框
    _sendSuccess(type) {
      var that = this
      this.$message({
        type: 'success',
        message: type === '0' ? '添加成功' : '更新成功'
      })
      this.show = false
      this.attendanceInfo = {}
      this.attSendTime = []
      this.setScore = ''
      that.$emit('getAllAttendanceInfo', type)
    },
    // 获取分数
    changeSendScore(e) {
      var that = this
      that.attendanceInfo.checkScore = e
      that.attendanceTypeInfo[0].checkTypeScore = e
    },
    // 时间转化
    dateReSend(d) {
      // 判断是否需要转化
      var isDateReSend = d.toString().search('-')
      if (isDateReSend !== -1) {
        return d
      } else {
        var rebackDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
        return rebackDate
      }
    },
    // 选择位置
    showSelectLocation() {
      if (this.attendanceInfo.checkPosition === undefined || this.attendanceInfo.checkPosition === '' || this.attendanceInfo.checkPosition === null) {
        // 添加
        this.$refs.selectLocation.showDialog(0, null)
      } else {
        // 修改

        const locationInfo = {
          latlng: {
            lat: this.attendanceInfo.checkLatitude,
            lng: this.attendanceInfo.checkLongitude
          },
          poinname: this.attendanceInfo.checkPosition
        }
        this.$refs.selectLocation.showDialog(1, locationInfo)
      }
    },
    // 设置位置
    setLocation(data) {
      var that = this
      that.attendanceInfo.checkLongitude = data.latlng.lng
      that.attendanceInfo.checkLatitude = data.latlng.lat
      that.$set(that.attendanceInfo, 'checkPosition', data.poiname)
    }
  }
}
</script>
<style lang="scss" scoped>
.from-infomations {
  margin-left: 1rem;
  margin-right: 1.5rem;
}
</style>
